package top.frsf.mqtt.handler.strategy;

import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.mqtt.MqttMessage;
import io.netty.handler.codec.mqtt.MqttMessageType;
import io.netty.handler.codec.mqtt.MqttUnsubscribeMessage;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import top.frsf.mqtt.handler.strategy.abs.MqttMessageHandlerStrategy;
import top.frsf.mqtt.session.SessionManager;

/**
 * MQTT协议事件 - 取消订阅事件处理器
 *
 * @author He Kuntao
 * @since 2025/5/30 11:40
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class UnsubscribeMessageHandler implements MqttMessageHandlerStrategy {

    private final SessionManager sessionManager;

    @Override
    public void handle(ChannelHandlerContext ctx, MqttMessage message) {
        MqttUnsubscribeMessage msg = (MqttUnsubscribeMessage) message;
        String clientId = sessionManager.getClientIdByChannel(ctx.channel());
        if (clientId == null) {
            ctx.close();
            return;
        }

        // 处理取消订阅
        for (String topic : msg.payload().topics()) {
            sessionManager.removeSubscription(topic, clientId);
            log.info("{} unsubscribed from {}", clientId, topic);
        }

        // 返回取消订阅确认
        ctx.writeAndFlush(createUnsubAck(msg.variableHeader().messageId()));
    }

    @Override
    public MqttMessageType supportedType() {
        return MqttMessageType.UNSUBSCRIBE;
    }
}
